<template>
  <div class="order_deliver_box">
    <span class="info_title">优惠</span>
    <span class="color-red" v-if="(activePro && ordinaryPro) || (discount !== 1)">*订单中含活动商品，不可使用代金券、红包抵扣券</span> 
    <span class="color-red" v-else-if="!ordinaryPro">*订单中全部商品参与活动不可使用代金券，红包抵扣券</span>
    <li>
      <span class="order_deliver_title">代金券 :</span>
      <button class="btn-choose daijinquan" 
        ref="daijinquan"
        :disabled="!voucherLen"
        :class="{'not_allow btn-disabled': !voucherLen}"
        @click="openVoucher('voucher')">{{voucherObj.id ? `满${voucherObj.limitAmount}减${voucherObj.amount}` : '请选择'}}</button>
      <el-checkbox v-model="neededVoucher" @change="inputRedeemCode"><span class="notice_text">输入兑换码</span></el-checkbox>
    </li>
    <transition>
      <li v-if="neededVoucher">
        <span class="order_deliver_title"></span>
        <el-input placeholder="请输入兑换码" v-model="deductionNumber" class="input_voucher" @change="getDeductionNumber"></el-input>
      </li>
    </transition>
    <li>
      <span class="order_deliver_title">红包抵扣 :</span>
      <button class="btn-choose hongbao"
        ref="hongbao" 
        :disabled="!discountLen"
        :class="{'not_allow btn-disabled': !discountLen}"
        @click="openVoucher('discount')">{{discountObj.id ? `${discountObj.amount}元` :'请选择'}} </button>
    </li>
    <li>
      <span class="order_deliver_title">运费券 :</span>
      <button class="btn-choose yunfeiquan" 
        ref="yunfeiquan"
        :disabled="!freightLen || resultDeliver === 0 || resultDeliver === 4"
        :class="{'not_allow btn-disabled': !freightLen || resultDeliver === 0 || resultDeliver === 4}"
        @click="openVoucher('freight')">{{freightObj.id ? `${freightObj.amount}元` :'请选择'}} </button>
    </li>
    <!-- 订单中存在缺货的商品selectedArr[index] -->
    <el-dialog :title="`选择${typeTitObj[currentType]}`" :show-close="false" :visible.sync="voucherVisible" width="520px" center>
      <ul class="discount_group">
        <template v-for="(item, index) in showList">
          <li class="discount_item"
            :key="index"
            :class="{'selected_icon': selectedArr[index]}"
            @click.stop="selectdVoucher(index)">
            <div class="discount_money">
              <span class="sum"><em class="unit">￥</em>{{item.amount}}</span>
              <span class="type">{{ item.type | typeName(item.brandLimit)}}</span>
              <p class="dashed"></p>
            </div>
            <div class="explains">
              <p>·{{currentType === 'voucher' ? `满${item.limitAmount}可使用` : '无门槛使用'}}</p>
              <p>·有效期：{{item.receivingTime | filterDate}} - {{item.overdueTime | filterDate}}</p>
            </div>
          </li>
        </template>
      </ul>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getVoucher">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {Checkbox, Dialog, Button, Input} from 'element-ui'
import {canUseDiscountList, getDeductlist, getFreightList} from '@/service/get-data'
export default {
  name: 'orderVoucher',
  components: {
    elCheckbox: Checkbox,
    elDialog: Dialog,
    elButton: Button,
    elInput: Input
  },
  props: {
    resultDeliver: {
      type: Number,
      default: 0
    },
    brandawardArr: {
      type: String,
      default: []
    },
    deliverType: {
      type: Number
    },
    discount: {
      type: Number,
      default: 1
    },
    isShowFriAndRed: {
      type: Boolean
    },
    ordinaryMoney: {
      type: Number
    },
    activePro: {
      type: Boolean
    },
    ordinaryPro: {
      type: Boolean
    }
  },
  data () {
    return {
      showList: [],
      currentType: 'voucher',
      typeTitObj: {voucher: '代金券', discount: '红包', freight: '运费券'},
      selectedArr: [],
      neededVoucher: false,
      voucherVisible: false,
      deductionNumber: '', // 兑换码
      voucherlist: [], // 代金券列表
      discountlist: [], // 红包券列表
      freightlist: [], // 运费券列表
      voucherObj: {},
      discountObj: {},
      freightObj: {}
    }
  },
  computed: {
    voucherLen () {
      return this.voucherlist.length > 0 && this.isShowFriAndRed
    },
    discountLen () {
      return this.discountlist.length && this.isShowFriAndRed
    },
    freightLen () {
      return this.freightlist.length
    }
  },
  methods: {
    // 获取优惠券列表
    async fetchDiscountList () {
      let res = await canUseDiscountList()
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.discountlist = res.data.data
        // this.discountObj = this.discountlist[0] || {}
        // if (!('id' in this.discountObj)) { return }
        // this.$emit('selectDiscount', {...this.discountObj})
      }
    },
    // 获取代金券列表 // getDeductlist获取可用优惠券列表接口
    async fetchVoucherList () {
      let res = await getDeductlist(this.brandawardArr, this.ordinaryMoney)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.voucherlist = res.data.data
        this.voucherObj = this.voucherlist[0] || {}
        if (!('id' in this.voucherObj)) { return }
        this.$emit('selectVoucher', {...this.voucherObj}, this.neededVoucher, this.deductionNumber)
      }
    },
    // 运费券列表
    async fetchFreightList () {
      let res = await getFreightList(1, 1000, 0)
      if (res.data.resultCode && res.data.resultCode === 2000) {
        this.freightlist = res.data.data.list
      }
    },
    // 点击选择优惠券
    openVoucher (type) {
      let selectArr = []
      let _idx
      this.showList = this[`${type}list`]
      let len = this.showList.length
      // 添加selected 属性
      this.showList.map((sitem, sidx) => {
        if (sitem.id === this[`${type}Obj`]['id']) {
          _idx = sidx
          sitem['selected'] = true
        } else {
          sitem['selected'] = false
        }
      })
      selectArr = new Array(len).fill(false)
      selectArr[_idx] = true
      this.selectedArr = selectArr
      this.currentType = type
      this.voucherVisible = true
    },
    selectdVoucher (idx) {
      let currStatus = [...this.selectedArr][idx]
      let selectArr = []
      // let _idx
      let len = this.selectedArr.length
      selectArr = new Array(len).fill(false)
      selectArr[idx] = !currStatus
      this.selectedArr = selectArr
      let currStatus2 = this.showList[idx]['selected']
      this.showList.map((item, indx) => {
        if (indx === idx) {
          item['selected'] = !currStatus2
        } else {
          item['selected'] = false
        }
      })
    },
    // 领取券
    getVoucher () {
      let _this = this
      let voucherObj = {}
      let discountObj = {}
      let freightObj = {}
      if (this.currentType === 'voucher') {
        this.voucherlist = [...this.showList]
        voucherObj = this.voucherlist.filter((vitem, vidx) => {
          return vitem.selected
        })
        this.voucherObj = {...voucherObj[0]}
        this.neededVoucher = false // 取消勾选兑换券
        this.$emit('selectVoucher', {...this.voucherObj}, _this.neededVoucher, _this.deductionNumber)
        this.voucherVisible = false
        return true
      }
      if (this.currentType === 'discount') {
        this.discountlist = [...this.showList]
        discountObj = this.discountlist.filter((ditem, didx) => {
          return ditem.selected
        })
        this.discountObj = {...discountObj[0]}
        this.$emit('selectDiscount', {...this.discountObj})
        this.voucherVisible = false
        return true
      }
      if (this.currentType === 'freight') {
        this.freightlist = [...this.showList]
        freightObj = this.freightlist.filter((ditem, didx) => {
          return ditem.selected
        })
        this.freightObj = {...freightObj[0]}
        this.$emit('selectFreight', [...freightObj])
        this.voucherVisible = false
        return true
      }
    },
    // 勾选兑换码
    inputRedeemCode (value) {
      console.log(value)
      if (this.neededVoucher) {
        this.voucherObj = {}
      } else {
        this.deductionNumber = ''
      }
      this.$emit('selectVoucher', {...this.voucherObj}, this.neededVoucher, this.deductionNumber)
    },
    getDeductionNumber () {
      this.$emit('selectVoucher', {}, this.neededVoucher, this.deductionNumber)
    }
  },
  mounted () {
    this.fetchFreightList()
    setTimeout(() => {
      if (this.isShowFriAndRed) {
        this.fetchDiscountList() // 获取代金券列表 延迟获取
        this.fetchVoucherList() // 获取优惠券列表
      }
    }, 1000)
  },
  filters: {
    typeName (type, limit) {
      let strarr = [['品牌券', '代金券'], '红包券', '运费券']
      if (type === 0) {
        return limit ? strarr[0][0] : strarr[0][1]
      }
      return strarr[type]
    },
    filterDate (value) {
      if (!value) return ''
      value = value.split(' ')[0]
      return value
    }
  },
  watch: {
    resultDeliver (newval) {
      if (newval === 0 || newval === 4) {
        this.freightObj = {}
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .order_deliver_box{
    position: relative;
    padding: 38px 0;
    color:#666666;
    overflow: hidden;
    @include border_bt();
    li {
      padding: 10px 0;
    }
    .order_font{
      color: RGBA(102, 102, 102, 1);
      font-size: 16px;
      line-height: 22px;
    }
    .order-text-box{
      float: right;
      margin-bottom: 10px;
    }
  }
  .info_title{
    display:inline-block;
    color: #333333;
    font-size: 18px;
    line-height: 25px;
    padding-right: 12px;
    margin-bottom: 12px;
    }
  .addr_info_tit{
    width: 64px;
    display: inline-block;
  }
  .order_deliver_title{
    font-size: 16px;
    width: 80px;
    display: inline-block;
  }
  .order_select{
    padding-right: 24px;
    padding-left: 8px;
  }
  .notice_text{
    cursor: pointer;
    font-size: 14px;
    color: #2A91D2;
  }
  .btn-choose{
    position: relative;
    border-radius: 2px;
    border: 1px solid #d8dce5;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    color: #5a5e66;
    display: inline-block;
    font-size: inherit;
    height: 40px;
    line-height: 1;
    outline: none;
    padding: 0 15px;
    line-height: 40px;
    width: 160px;
    background: #fff;
    text-align: left;
    &:after{
      font-family: 'element-icons';
      color: #999999;
      position: absolute;
      right: 5px;
      top: 0;
      content: "\E603";
    }
    &.btn-disabled{
      background: #F3F3F3;
      color: #999;
    }
  }
  .input_voucher{
    width:160px;
    padding-right: 20px;
    // padding-left: 8px;
  }
  .discount{
    &_group{
      overflow: hidden;
      // margin-bottom: 20px;
      overflow-y: auto;
      max-height: 280px;
    }
    &_money{
      background: linear-gradient(180deg, #FFBC00, #FF8600);
      padding: 5px 0 3px;
      text-align: center;
      color: #fff;
      .sum{
        @include fontbase(#fff, 40px, 50px);
        width: 50%;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
      }
      .type{
        width: 36%;
        text-align: right;
        display: inline-block;
        vertical-align: middle;
      }
      .unit{
        @include fontbase(#fff, 18px, 25px);
      }
      .condition{
        @include fontbase(#fff, 12px, 17px);
        margin-bottom: 10px;
      }
      .dashed{
        border-bottom: 1px dashed #ffffff;
      }
    }
    &_item{
      position: relative;
      margin-right: 20px;
      float: left;
      width: 46%;
      // margin-bottom: 10px;
      cursor: pointer;
      &:nth-child(2n){
        margin-right: 0;
      }
      .explains{
        padding: 11px;
        border:1px solid #d8d8d8;
        border-top: none;
        @include fontbase(#666666, 12px, 17px);
      }
    }
  }
  .selected_icon{
    position: relative;
    &:after{
      font-family: element-icons;
      position: absolute;
      top: -2px;
      right: -4px;
      content: '\E63E';
      color: #ff0000;
      background: #fff;
      width: 30px;
      height: 30px;
      font-size: 28px;
      text-align: center;
      border-radius: 50%;
      line-height: 30px;
    }
  }
</style>
